<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="../../aosa.css" type="text/css">
    <title>500 Lines or Less: Optical Character Recognition</title>
  </head>
  <body>

    <div class="titlebox">
      <h1>500 Lines or Less<br>Optical Character Recognition</h1>
      <p class="author">Marina Samuel</p>
    </div>

    <h2 id="introduction">Introduction</h2>

<p>What if your computer could wash your dishes, do your laundry, cook you dinner, and clean your home? I think I can safely say that most people would be happy to get a helping hand! But what would it take for a computer to be able to perform these tasks in the same way that humans can?</p>

<p>The famous computer scientist Alan Turing proposed the Turing Test as a way to identify whether a machine could have intelligence indistinguishable from that of a human being. The test involves a human posing questions to two hidden entities, one human, and the other a machine, and trying to identify which is which. If the interrogator is unable to identify the machine, then the machine is considered to have human-level intelligence.</p>

<p>While there is a lot of controversy surrounding whether the Turing Test is a valid assessment of intelligence, and whether we can build such intelligent machines, there is no doubt that machines with some degree of intelligence already exist. There is currently software that helps robots navigate an office and perform small tasks, or help those suffering with Alzheimer's. More common examples of Artificial Intelligence (A.I.) are the way that Google estimates what you’re looking for when you search for some keywords, or the way that Facebook decides what to put in your news feed.</p>

<p>One well known application of A.I. is Optical Character Recognition (OCR). An OCR system is a piece of software that can take images of handwritten characters as input and interpret them into machine readable text. While you may not think twice when depositing a handwritten cheque into a bank machine , there is some interesting work going on in the background. This chapter will examine a working example of a simple OCR system that recognizes numerical digits using an Artificial Neural Network (ANN). But first, let’s establish a bit more context.</p>

<h2 id="what-is-artificial-intelligence">What is Artificial Intelligence?</h2>

<p><a name="sec.ocr.ai"> </a> While Turing’s definition of intelligence sounds reasonable, at the end of the day what constitutes intelligence is fundamentally a philosophical debate. Computer scientists have, however, categorized certain types of systems and algorithms into branches of AI. Each branch is used to solve certain sets of problems. These branches include the following examples, as well as <a href="http://www-formal.stanford.edu/jmc/whatisai/node2.html">many others</a>:</p>

<ul>
<li>Logical and probabilistic deduction and inference based on some predefined knowledge of a world. e.g. <a href="http://www.cs.princeton.edu/courses/archive/fall07/cos436/HIDDEN/Knapp/fuzzy004.htm">Fuzzy inference</a> can help a thermostat decide when to turn on the air conditioning when it detects that the temperature is hot and the atmosphere is humid</li>
<li>Heuristic search. e.g. Searching can be used to find the best possible next move in a game of chess by searching all possible moves and choosing the one that most improves your position</li>
<li>Machine learning (ML) with feedback models. e.g. Pattern-recognition problems like OCR.</li>
</ul>

<p>In general, ML involves using large data sets to train a system to identify patterns. The training data sets may be labelled, meaning the system’s expected outputs are specified for given inputs, or unlabelled meaning expected outputs are not specified. Algorithms that train systems with unlabelled data are called <em>unsupervised</em> algorithms and those that train with labelled data are called <em>supervised</em>. Many ML algorithms and techniques exist for creating OCR systems, of which ANNs are one approach.</p>

<h2 id="artificial-neural-networks">Artificial Neural Networks</h2>

<h3 id="what-are-anns">What Are ANNs?</h3>

<p><a name="sec.ocr.ann"> </a> An ANN is a structure consisting of interconnected nodes that communicate with one another. The structure and its functionality are inspired by neural networks found in a biological brain. <a href="http://www.nbb.cornell.edu/neurobio/linster/BioNB420/hebb.pdf">Hebbian Theory</a> explains how these networks can learn to identify patterns by physically altering their structure and link strengths. Similarly, a typical ANN (shown in <a href="#figure-15.1">Figure 15.1</a>) has connections between nodes that have a weight which is updated as the network learns. The nodes labelled &quot;+1&quot; are called <em>biases</em>. The leftmost blue column of nodes are <em>input nodes</em>, the middle column contains <em>hidden nodes</em>, and the rightmost column contains <em>output nodes</em>. There may be many columns of hidden nodes, known as <em>hidden layers</em>.</p>

<div class="center figure">
<a name="figure-15.1"></a><img src="ocr-images/ann.png" alt="Figure 15.1 - An Artificial Neural Network" title="Figure 15.1 - An Artificial Neural Network" />
</div>

<p class="center figcaption">
<small>Figure 15.1 - An Artificial Neural Network</small>
</p>

<p>The values inside all of the circular nodes in <a href="#figure-15.1">Figure 15.1</a> represent the output of the node. If we call the output of the <span class="math">\(n\)</span>th node from the top in layer <span class="math">\(L\)</span> as a <span class="math">\(n(L)\)</span> and the connection between the <span class="math">\(i\)</span>th node in layer <span class="math">\(L\)</span> and the <span class="math">\(j\)</span>th node in layer <span class="math">\(L+1\)</span> as <span class="math">\(w^{(L)}_ji\)</span>, then the output of node <span class="math">\(a^{(2)}_2\)</span> is:</p>

<p><span class="math">\[
a^{(2)}_2 = f(w^{(1)}_{21}x_1 + w^{(1)}_{22}x_2 + b^{(1)}_{2})
\]</span></p>

<p>where <span class="math">\(f(.)\)</span> is known as the <em>activation function</em> and <span class="math">\(b\)</span> is the <em>bias</em>. An activation function is the decision-maker for what type of output a node has. A bias is an additional node with a fixed output of 1 that may be added to an ANN to improve its accuracy. We’ll see more details on both of these in <a href="#sec.ocr.feedforward">Designing a Feedforward ANN (<code>neural_network_design.py</code>)</a>.</p>

<p>This type of network topology is called a <em>feedforward</em> neural network because there are no cycles in the network. ANNs with nodes whose outputs feed into their inputs are called recurrent neural networks. There are many algorithms that can be applied to train feedforward ANNs; one commonly used algorithm is called <em>backpropagation</em>. The OCR system we will implement in this chapter will use backpropagation.</p>

<h3 id="how-do-we-use-anns">How Do We Use ANNs?</h3>

<p>Like most other ML approaches, the first step for using backpropagation is to decide how to transform or reduce our problem into one that can be solved by an ANN. In other words, how can we manipulate our input data so we can feed it into the ANN? For the case of our OCR system, we can use the positions of the pixels for a given digit as input. It is worth noting that, often times, choosing the input data format is not this simple. If we were analyzing large images to identify shapes in them, for instance, we may need to pre-process the image to identify contours within it. These contours would be the input.</p>

<p>Once we’ve decided on our input data format, what’s next? Since backpropagation is a supervised algorithm, it will need to be trained with labelled data, as mentioned in <a href="#sec.ocr.ai">What is Artificial Intelligence?</a>. Thus, when passing the pixel positions as training input, we must also pass the associated digit. This means that we must find or gather a large data set of drawn digits and associated values.</p>

<p>The next step is to partition the data set into a training set and validation set. The training data is used to run the backpropagation algorithm to set the weights of the ANN. The validation data is used to make predictions using the trained network and compute its accuracy. If we were comparing the performance of backpropagation vs. another algorithm on our data, we would <a href="http://www-group.slac.stanford.edu/sluo/Lectures/stat_lecture_files/sluo2006lec7.pdf">split the data</a> into 50% for training, 25% for comparing performance of the 2 algorithms (validation set) and the final 25% for testing accuracy of the chosen algorithm (test set). Since we’re not comparing algorithms, we can group one of the 25% sets as part of the training set and use 75% of the data to train the network and 25% for validating that it was trained well.</p>

<p>The purpose of identifying the accuracy of the ANN is two-fold. First, it is to avoid the problem of <em>overfitting</em>. Overfitting occurs when the network has a much higher accuracy on predicting the training set than the validation set. Overfitting tells us that the chosen training data does not generalize well enough and needs to be refined. Secondly, testing the accuracy of several different numbers of hidden layers and hidden nodes helps in designing the most optimal ANN size. An optimal ANN size will have enough hidden nodes and layers to make accurate predictions but also as few nodes/connections as possible to reduce computational overhead that may slow down training and predictions. Once the optimal size has been decided and the network has been trained, it’s ready to make predictions!</p>

<h2 id="design-decisions-in-a-simple-ocr-system">Design Decisions in a Simple OCR System</h2>

<p><a name="sec.ocr.decisions"> </a> In the last few paragraphs we’ve gone over some of the basics of feedforward ANNs and how to use them. Now it’s time to talk about how we can build an OCR system.</p>

<p>First off, we must decide what we want our system to be able to do. To keep things simple, let’s allow users to draw a single digit and be able to train the OCR system with that drawn digit or to request that the system predict what the drawn digit is. While an OCR system could run locally on a single machine, having a client-server setup gives much more flexibility. It makes crowd-sourced training of an ANN possible and allows powerful servers to handle intensive computations.</p>

<p>Our OCR system will consist of 5 main components, divided into 5 files. There will be:</p>

<ul>
<li>a client (<code>ocr.js</code>)</li>
<li>a server (<code>server.py</code>)</li>
<li>a simple user interface (<code>ocr.html</code>)</li>
<li>an ANN trained via backpropagation (<code>ocr.py</code>)</li>
<li>an ANN design script (<code>neural_network_design.py</code>)</li>
</ul>

<p>The user interface will be simple: a canvas to draw digits on and buttons to either train the ANN or request a prediction. The client will gather the drawn digit, translate it into an array, and pass it to the server to be processed either as a training sample or as a prediction request. The server will simply route the training or prediction request by making API calls to the ANN module. The ANN module will train the network with an existing data set on its first initialization. It will then save the ANN weights to a file and re-load them on subsequent startups. This module is where the core of training and prediction logic happens. Finally, the design script is for experimenting with different hidden node counts and deciding what works best. Together, these pieces give us a very simplistic, but functional OCR system.</p>

<p>Now that we've thought about how the system will work at a high level, it's time to put the concepts into code!</p>

<h3 id="a-simple-interface-ocr.html">A Simple Interface (<code>ocr.html</code>)</h3>

<p>As mentioned earlier, the first step is to gather data for training the network. We could upload a sequence of hand-written digits to the server, but that would be awkward. Instead, we could have users actually handwrite the digits on the page using an HTML canvas. We could then give them a couple of options to either train or test the network, where training the network also involves specifying what digit was drawn. This way it is possible to easily outsource the data collection by pointing people to a website to receive their input. Here’s some HTML to get us started.</p>

<pre class="sourceCode html"><code class="sourceCode html"><span class="kw">&lt;html&gt;</span>
<span class="kw">&lt;head&gt;</span>
    <span class="kw">&lt;script</span><span class="ot"> src=</span><span class="st">&quot;ocr.js&quot;</span><span class="kw">&gt;&lt;/script&gt;</span>
    <span class="kw">&lt;link</span><span class="ot"> rel=</span><span class="st">&quot;stylesheet&quot;</span><span class="ot"> type=</span><span class="st">&quot;text/css&quot;</span><span class="ot"> href=</span><span class="st">&quot;ocr.css&quot;</span><span class="kw">&gt;</span>
<span class="kw">&lt;/head&gt;</span>
<span class="kw">&lt;body</span><span class="ot"> onload=</span><span class="st">&quot;ocrDemo.onLoadFunction()&quot;</span><span class="kw">&gt;</span>
    <span class="kw">&lt;div</span><span class="ot"> id=</span><span class="st">&quot;main-container&quot;</span><span class="ot"> style=</span><span class="st">&quot;text-align: center;&quot;</span><span class="kw">&gt;</span>
        <span class="kw">&lt;h1&gt;</span>OCR Demo<span class="kw">&lt;/h1&gt;</span>
        <span class="kw">&lt;canvas</span><span class="ot"> id=</span><span class="st">&quot;canvas&quot;</span><span class="ot"> width=</span><span class="st">&quot;200&quot;</span><span class="ot"> height=</span><span class="st">&quot;200&quot;</span><span class="kw">&gt;&lt;/canvas&gt;</span>
        <span class="kw">&lt;form</span><span class="ot"> name=</span><span class="st">&quot;input&quot;</span><span class="kw">&gt;</span>
            <span class="kw">&lt;p&gt;</span>Digit: <span class="kw">&lt;input</span><span class="ot"> id=</span><span class="st">&quot;digit&quot;</span><span class="ot"> type=</span><span class="st">&quot;text&quot;</span><span class="kw">&gt;</span> <span class="kw">&lt;/p&gt;</span>
            <span class="kw">&lt;input</span><span class="ot"> type=</span><span class="st">&quot;button&quot;</span><span class="ot"> value=</span><span class="st">&quot;Train&quot;</span><span class="ot"> onclick=</span><span class="st">&quot;ocrDemo.train()&quot;</span><span class="kw">&gt;</span>
            <span class="kw">&lt;input</span><span class="ot"> type=</span><span class="st">&quot;button&quot;</span><span class="ot"> value=</span><span class="st">&quot;Test&quot;</span><span class="ot"> onclick=</span><span class="st">&quot;ocrDemo.test()&quot;</span><span class="kw">&gt;</span>
            <span class="kw">&lt;input</span><span class="ot"> type=</span><span class="st">&quot;button&quot;</span><span class="ot"> value=</span><span class="st">&quot;Reset&quot;</span><span class="ot"> onclick=</span><span class="st">&quot;ocrDemo.resetCanvas();&quot;</span><span class="kw">/&gt;</span>
        <span class="kw">&lt;/form&gt;</span> 
    <span class="kw">&lt;/div&gt;</span>
<span class="kw">&lt;/body&gt;</span>
<span class="kw">&lt;/html&gt;</span></code></pre>

<h3 id="an-ocr-client-ocr.js">An OCR Client (<code>ocr.js</code>)</h3>

<p>Since a single pixel on an HTML canvas might be hard to see, we can represent a single pixel for the ANN input as a square of 10x10 real pixels. Thus the real canvas is 200x200 pixels and it is represented by a 20x20 canvas from the perspective of the ANN. The variables below will help us keep track of these measurements.</p>

<pre class="sourceCode javascript"><code class="sourceCode javascript"><span class="kw">var</span> ocrDemo = {
    <span class="dt">CANVAS_WIDTH</span>: <span class="dv">200</span>,
    <span class="dt">TRANSLATED_WIDTH</span>: <span class="dv">20</span>,
    <span class="dt">PIXEL_WIDTH</span>: <span class="dv">10</span>, <span class="co">// TRANSLATED_WIDTH = CANVAS_WIDTH / PIXEL_WIDTH</span></code></pre>

<p>We can then outline the pixels in the new representation so they are easier to see. Here we have a blue grid generated by <code>drawGrid()</code>.</p>

<pre class="sourceCode javascript"><code class="sourceCode javascript">    drawGrid: <span class="kw">function</span>(ctx) {
        <span class="kw">for</span> (<span class="kw">var</span> x = <span class="kw">this</span>.<span class="fu">PIXEL_WIDTH</span>, y = <span class="kw">this</span>.<span class="fu">PIXEL_WIDTH</span>; 
                 x &lt; <span class="kw">this</span>.<span class="fu">CANVAS_WIDTH</span>; x += <span class="kw">this</span>.<span class="fu">PIXEL_WIDTH</span>, 
                 y += <span class="kw">this</span>.<span class="fu">PIXEL_WIDTH</span>) {
            <span class="ot">ctx</span>.<span class="fu">strokeStyle</span> = <span class="kw">this</span>.<span class="fu">BLUE</span>;
            <span class="ot">ctx</span>.<span class="fu">beginPath</span>();
            <span class="ot">ctx</span>.<span class="fu">moveTo</span>(x, <span class="dv">0</span>);
            <span class="ot">ctx</span>.<span class="fu">lineTo</span>(x, <span class="kw">this</span>.<span class="fu">CANVAS_WIDTH</span>);
            <span class="ot">ctx</span>.<span class="fu">stroke</span>();

            <span class="ot">ctx</span>.<span class="fu">beginPath</span>();
            <span class="ot">ctx</span>.<span class="fu">moveTo</span>(<span class="dv">0</span>, y);
            <span class="ot">ctx</span>.<span class="fu">lineTo</span>(<span class="kw">this</span>.<span class="fu">CANVAS_WIDTH</span>, y);
            <span class="ot">ctx</span>.<span class="fu">stroke</span>();
        }
    },</code></pre>

<p>We also need to store the data drawn on the grid in a form that can be sent to the server. For simplicity, we can have an array called <code>data</code> which labels an uncoloured, black pixel as <code>0</code> and a coloured white pixel as <code>1</code>. We also need some mouse listeners on the canvas so we know when to call <code>fillSquare()</code> to colour a pixel white while a user is drawing a digit. These listeners should keep track of whether we are in a drawing state and then call <code>fillSquare()</code> to do some simple math and decide which pixels need to be filled in.</p>

<pre class="sourceCode javascript"><code class="sourceCode javascript">    onMouseMove: <span class="kw">function</span>(e, ctx, canvas) {
        <span class="kw">if</span> (!<span class="ot">canvas</span>.<span class="fu">isDrawing</span>) {
            <span class="kw">return</span>;
        }
        <span class="kw">this</span>.<span class="fu">fillSquare</span>(ctx, 
            <span class="ot">e</span>.<span class="fu">clientX</span> - <span class="ot">canvas</span>.<span class="fu">offsetLeft</span>, <span class="ot">e</span>.<span class="fu">clientY</span> - <span class="ot">canvas</span>.<span class="fu">offsetTop</span>);
    },

    onMouseDown: <span class="kw">function</span>(e, ctx, canvas) {
        <span class="ot">canvas</span>.<span class="fu">isDrawing</span> = <span class="kw">true</span>;
        <span class="kw">this</span>.<span class="fu">fillSquare</span>(ctx, 
            <span class="ot">e</span>.<span class="fu">clientX</span> - <span class="ot">canvas</span>.<span class="fu">offsetLeft</span>, <span class="ot">e</span>.<span class="fu">clientY</span> - <span class="ot">canvas</span>.<span class="fu">offsetTop</span>);
    },

    onMouseUp: <span class="kw">function</span>(e) {
        <span class="ot">canvas</span>.<span class="fu">isDrawing</span> = <span class="kw">false</span>;
    },

    fillSquare: <span class="kw">function</span>(ctx, x, y) {
        <span class="kw">var</span> xPixel = <span class="ot">Math</span>.<span class="fu">floor</span>(x / <span class="kw">this</span>.<span class="fu">PIXEL_WIDTH</span>);
        <span class="kw">var</span> yPixel = <span class="ot">Math</span>.<span class="fu">floor</span>(y / <span class="kw">this</span>.<span class="fu">PIXEL_WIDTH</span>);
        <span class="kw">this</span>.<span class="fu">data</span>[((xPixel - <span class="dv">1</span>)  * <span class="kw">this</span>.<span class="fu">TRANSLATED_WIDTH</span> + yPixel) - <span class="dv">1</span>] = <span class="dv">1</span>;

        <span class="ot">ctx</span>.<span class="fu">fillStyle</span> = <span class="st">&#39;#ffffff&#39;</span>;
        <span class="ot">ctx</span>.<span class="fu">fillRect</span>(xPixel * <span class="kw">this</span>.<span class="fu">PIXEL_WIDTH</span>, yPixel * <span class="kw">this</span>.<span class="fu">PIXEL_WIDTH</span>, 
            <span class="kw">this</span>.<span class="fu">PIXEL_WIDTH</span>, <span class="kw">this</span>.<span class="fu">PIXEL_WIDTH</span>);
    },</code></pre>

<p>Now we’re getting closer to the juicy stuff! We need a function that prepares training data to be sent to the server. Here we have a relatively straight forward <code>train()</code> function that does some error checking on the data to be sent, adds it to <code>trainArray</code> and sends it off by calling <code>sendData()</code>.</p>

<pre class="sourceCode javascript"><code class="sourceCode javascript">    train: <span class="kw">function</span>() {
        <span class="kw">var</span> digitVal = <span class="ot">document</span>.<span class="fu">getElementById</span>(<span class="st">&quot;digit&quot;</span>).<span class="fu">value</span>;
        <span class="kw">if</span> (!digitVal || <span class="kw">this</span>.<span class="ot">data</span>.<span class="fu">indexOf</span>(<span class="dv">1</span>) &lt; <span class="dv">0</span>) {
            <span class="fu">alert</span>(<span class="st">&quot;Please type and draw a digit value in order to train the network&quot;</span>);
            <span class="kw">return</span>;
        }
        <span class="kw">this</span>.<span class="ot">trainArray</span>.<span class="fu">push</span>({<span class="st">&quot;y0&quot;</span>: <span class="kw">this</span>.<span class="fu">data</span>, <span class="st">&quot;label&quot;</span>: <span class="fu">parseInt</span>(digitVal)});
        <span class="kw">this</span>.<span class="fu">trainingRequestCount</span>++;

        <span class="co">// Time to send a training batch to the server.</span>
        <span class="kw">if</span> (<span class="kw">this</span>.<span class="fu">trainingRequestCount</span> == <span class="kw">this</span>.<span class="fu">BATCH_SIZE</span>) {
            <span class="fu">alert</span>(<span class="st">&quot;Sending training data to server...&quot;</span>);
            <span class="kw">var</span> json = {
                <span class="dt">trainArray</span>: <span class="kw">this</span>.<span class="fu">trainArray</span>,
                <span class="dt">train</span>: <span class="kw">true</span>
            };

            <span class="kw">this</span>.<span class="fu">sendData</span>(json);
            <span class="kw">this</span>.<span class="fu">trainingRequestCount</span> = <span class="dv">0</span>;
            <span class="kw">this</span>.<span class="fu">trainArray</span> = [];
        }
    },</code></pre>

<p>An interesting design worth noting here is the use of <code>trainingRequestCount</code>, <code>trainArray</code>, and <code>BATCH_SIZE</code>. What’s happening here is that <code>BATCH_SIZE</code> is some pre-defined constant for how much training data a client will keep track of before it sends a batched request to the server to be processed by the OCR. The main reason to batch requests is to avoid overwhelming the server with many requests at once. If many clients exist (e.g. many users are on the <code>ocr.html</code> page training the system), or if another layer existed in the client that takes scanned drawn digits and translated them to pixels to train the network, a <code>BATCH_SIZE</code> of 1 would result in many, unnecessary requests. This approach is good because it gives more flexibility to the client, however, in practice, batching should also take place on the server, when needed. A denial of service (DoS) attack could occur in which a malicious client purposely sends many requests to the server to overwhelm it so that it breaks down.</p>

<p>We will also need a <code>test()</code> function. Similar to <code>train()</code>, it should do a simple check on the validity of the data and send it off. For <code>test()</code>, however, no batching occurs since users should be able to request a prediction and get immediate results.</p>

<pre class="sourceCode javascript"><code class="sourceCode javascript">    test: <span class="kw">function</span>() {
        <span class="kw">if</span> (<span class="kw">this</span>.<span class="ot">data</span>.<span class="fu">indexOf</span>(<span class="dv">1</span>) &lt; <span class="dv">0</span>) {
            <span class="fu">alert</span>(<span class="st">&quot;Please draw a digit in order to test the network&quot;</span>);
            <span class="kw">return</span>;
        }
        <span class="kw">var</span> json = {
            <span class="dt">image</span>: <span class="kw">this</span>.<span class="fu">data</span>,
            <span class="dt">predict</span>: <span class="kw">true</span>
        };
        <span class="kw">this</span>.<span class="fu">sendData</span>(json);
    },</code></pre>

<p>Finally, we will need some functions to make an HTTP POST request, receive a response, and handle any potential errors along the way.</p>

<pre class="sourceCode javascript"><code class="sourceCode javascript">    receiveResponse: <span class="kw">function</span>(xmlHttp) {
        <span class="kw">if</span> (<span class="ot">xmlHttp</span>.<span class="fu">status</span> != <span class="dv">200</span>) {
            <span class="fu">alert</span>(<span class="st">&quot;Server returned status &quot;</span> + <span class="ot">xmlHttp</span>.<span class="fu">status</span>);
            <span class="kw">return</span>;
        }
        <span class="kw">var</span> responseJSON = <span class="ot">JSON</span>.<span class="fu">parse</span>(<span class="ot">xmlHttp</span>.<span class="fu">responseText</span>);
        <span class="kw">if</span> (<span class="ot">xmlHttp</span>.<span class="fu">responseText</span> &amp;&amp; <span class="ot">responseJSON</span>.<span class="fu">type</span> == <span class="st">&quot;test&quot;</span>) {
            <span class="fu">alert</span>(<span class="st">&quot;The neural network predicts you wrote a </span><span class="ch">\&#39;</span><span class="st">&quot;</span> 
                   + <span class="ot">responseJSON</span>.<span class="fu">result</span> + <span class="st">&#39;</span><span class="ch">\&#39;</span><span class="st">&#39;</span>);
        }
    },

    onError: <span class="kw">function</span>(e) {
        <span class="fu">alert</span>(<span class="st">&quot;Error occurred while connecting to server: &quot;</span> + <span class="ot">e</span>.<span class="ot">target</span>.<span class="fu">statusText</span>);
    },

    sendData: <span class="kw">function</span>(json) {
        <span class="kw">var</span> xmlHttp = <span class="kw">new</span> <span class="fu">XMLHttpRequest</span>();
        <span class="ot">xmlHttp</span>.<span class="fu">open</span>(<span class="st">&#39;POST&#39;</span>, <span class="kw">this</span>.<span class="fu">HOST</span> + <span class="st">&quot;:&quot;</span> + <span class="kw">this</span>.<span class="fu">PORT</span>, <span class="kw">false</span>);
        <span class="ot">xmlHttp</span>.<span class="fu">onload</span> = <span class="kw">function</span>() { <span class="kw">this</span>.<span class="fu">receiveResponse</span>(xmlHttp); }.<span class="fu">bind</span>(<span class="kw">this</span>);
        <span class="ot">xmlHttp</span>.<span class="fu">onerror</span> = <span class="kw">function</span>() { <span class="kw">this</span>.<span class="fu">onError</span>(xmlHttp) }.<span class="fu">bind</span>(<span class="kw">this</span>);
        <span class="kw">var</span> msg = <span class="ot">JSON</span>.<span class="fu">stringify</span>(json);
        <span class="ot">xmlHttp</span>.<span class="fu">setRequestHeader</span>(<span class="st">&#39;Content-length&#39;</span>, <span class="ot">msg</span>.<span class="fu">length</span>);
        <span class="ot">xmlHttp</span>.<span class="fu">setRequestHeader</span>(<span class="st">&quot;Connection&quot;</span>, <span class="st">&quot;close&quot;</span>);
        <span class="ot">xmlHttp</span>.<span class="fu">send</span>(msg);
    }</code></pre>

<h3 id="a-server-server.py">A Server (<code>server.py</code>)</h3>

<p>Despite being a small server that simply relays information, we still need to consider how to receive and handle the HTTP requests. First we need to decide what kind of HTTP request to use. In the last section, the client is using POST, but why did we decide on this? Since data is being sent to the server, a PUT or POST request makes the most sense. We only need to send a json body and no URL parameters. So in theory, a GET request could have worked as well but would not make sense semantically. The choice between PUT and POST, however, is a long, on-going debate among programmers; KNPLabs summarizes the issues <a href="https://knpuniversity.com/screencast/rest/put-versus-post">with humour</a>.</p>

<p>Another consideration is whether to send the &quot;train&quot; vs. &quot;predict&quot; requests to different endpoints (e.g. <code>http://localhost/train</code> and <code>http://localhost/predict</code>) or the same endpoint which then processes the data separately. In this case, we can go with the latter approach since the difference between what is done with the data in each case is minor enough to fit into a short if statement. In practice, it would be better to have these as separate endpoints if the server were to do any more detailed processing for each request type. This decision, in turn impacted what server error codes were used when. For example, a 400 &quot;Bad Request&quot; error is sent when neither &quot;train&quot; or &quot;predict&quot; is specified in the payload. If separate endpoints were used instead, this would not be an issue. The processing done in the background by the OCR system may fail for any reason and if it's not handled correctly within the server, a 500 &quot;Internal Server Error&quot; is sent. Again, if the endpoints were separated, there would have been more room to go into detail to send more appropriate errors. For example, identifying that an internal server error was actually caused by a bad request.</p>

<p>Finally, we need to decide when and where to initialize the OCR system. A good approach would be to initialize it within <code>server.py</code> but before the server is started. This is because on first run, the OCR system needs to train the network on some pre-existing data the first time it starts and this may take a few minutes. If the server started before this processing was complete, any requests to train or predict would throw an exception since the OCR object would not yet have been initialized, given the current implementation. Another possible implementation could create some inaccurate initial ANN to be used for the first few queries while the new ANN is asynchronously trained in the background. This alternative approach does allow the ANN to be used immediately, but the implementation is more complex and it would only save on time on server startup if the servers are reset. This type of implementation would be more beneficial for an OCR service that requires high availability.</p>

<p>Here we have the majority of our server code in one short function that handles POST requests.</p>

<pre class="sourceCode python"><code class="sourceCode python">    <span class="kw">def</span> do_POST(s):
        response_code = <span class="dv">200</span>
        response = <span class="st">&quot;&quot;</span>
        var_len = <span class="dt">int</span>(s.headers.get(<span class="st">&#39;Content-Length&#39;</span>))
        content = s.rfile.read(var_len);
        payload = json.loads(content);

        <span class="kw">if</span> payload.get(<span class="st">&#39;train&#39;</span>):
            nn.train(payload[<span class="st">&#39;trainArray&#39;</span>])
            nn.save()
        <span class="kw">elif</span> payload.get(<span class="st">&#39;predict&#39;</span>):
            <span class="kw">try</span>:
                response = {
                    <span class="st">&quot;type&quot;</span>:<span class="st">&quot;test&quot;</span>, 
                    <span class="co">&quot;result&quot;</span>:nn.predict(<span class="dt">str</span>(payload[<span class="st">&#39;image&#39;</span>]))
                }
            <span class="kw">except</span>:
                response_code = <span class="dv">500</span>
        <span class="kw">else</span>:
            response_code = <span class="dv">400</span>

        s.send_response(response_code)
        s.send_header(<span class="st">&quot;Content-type&quot;</span>, <span class="st">&quot;application/json&quot;</span>)
        s.send_header(<span class="st">&quot;Access-Control-Allow-Origin&quot;</span>, <span class="st">&quot;*&quot;</span>)
        s.end_headers()
        <span class="kw">if</span> response:
            s.wfile.write(json.dumps(response))
        <span class="kw">return</span></code></pre>

<h3 id="designing-a-feedforward-ann-neural_network_design.py">Designing a Feedforward ANN (<code>neural_network_design.py</code>)</h3>

<p><a name="sec.ocr.feedforward"> </a> When designing a feedforward ANN, there are a few factors we must consider. The first is what activation function to use. We mentioned activation functions earlier as the decision-maker for a node’s output. The type of the decision an activation function makes will help us decide which one to use. In our case, we will be designing an ANN that outputs a value between 0 and 1 for each digit (0-9). Values closer to 1 would mean the ANN predicts this is the drawn digit and values closer to 0 would mean it’s predicted to not be the drawn digit. Thus, we want an activation function that would have outputs either close to 0 or close to 1. We also need a function that is differentiable because we will need the derivative for our backpropagation computation. A commonly used function in this case is the sigmoid because it satisfies both these constraints. StatSoft provides a <a href="http://www.fmi.uni-sofia.bg/fmi/statist/education/textbook/eng/glosa.html">nice list</a> of common activation functions and their properties.</p>

<p>A second factor to consider is whether we want to include biases. We've mentioned biases a couple of times before but haven't really talked about what they are or why we use them. Let's try to understand this by going back to how the output of a node is computed in <a href="#figure-15.1">Figure 15.1</a>. Suppose we had a single input node and a single output node, our output formula would be <span class="math">\(y = f(wx)\)</span>, where <span class="math">\(y\)</span> is the output, <span class="math">\(f()\)</span> is the activation function, <span class="math">\(w\)</span> is the weight for the link between the nodes, and <span class="math">\(x\)</span> is the variable input for the node. The bias is essentially a node whose output is always <span class="math">\(1\)</span>. This would change the output formula to <span class="math">\(y = f(wx + b)\)</span> where <span class="math">\(b\)</span> is the weight of the connection between the bias node and the next node. If we consider <span class="math">\(w\)</span> and <span class="math">\(b\)</span> as constants and <span class="math">\(x\)</span> as a variable, then adding a bias adds a constant to our linear function input to <span class="math">\(f(.)\)</span>.</p>

<p>Adding the bias therefore allows for a shift in the <span class="math">\(y\)</span>-intercept and in general gives more flexibility for the output of a node. It's often good practice to include biases, especially for ANNs with a small number of inputs and outputs. Biases allow for more flexibility in the output of the ANN and thus provide the ANN with more room for accuracy. Without biases, we’re less likely to make correct predictions with our ANN or would need more hidden nodes to make more accurate predictions.</p>

<p>Other factors to consider are the number of hidden layers and the number of hidden nodes per layer. For larger ANNs with many inputs and outputs, these numbers are decided by trying different values and testing the network's performance. In this case, the performance is measured by training an ANN of a given size and seeing what percentage of the validation set is classified correctly. In most cases, a single hidden layer is sufficient for decent performance, so we only experiment with the number of hidden nodes here.</p>

<pre class="sourceCode python"><code class="sourceCode python"><span class="co"># Try various number of hidden nodes and see what performs best</span>
<span class="kw">for</span> i in <span class="dt">xrange</span>(<span class="dv">5</span>, <span class="dv">50</span>, <span class="dv">5</span>):
    nn = OCRNeuralNetwork(i, data_matrix, data_labels, train_indices, <span class="ot">False</span>)
    performance = <span class="dt">str</span>(test(data_matrix, data_labels, test_indices, nn))
    <span class="dt">print</span> <span class="st">&quot;</span><span class="ot">{i}</span><span class="st"> Hidden Nodes: </span><span class="ot">{val}</span><span class="st">&quot;</span>.<span class="dt">format</span>(i=i, val=performance)</code></pre>

<p>Here we initialize an ANN with between 5 to 50 hidden nodes in increments of 5. We then call the <code>test()</code> function.</p>

<pre class="sourceCode python"><code class="sourceCode python"><span class="kw">def</span> test(data_matrix, data_labels, test_indices, nn):
    avg_sum = <span class="dv">0</span>
    <span class="kw">for</span> j in <span class="dt">xrange</span>(<span class="dv">100</span>):
        correct_guess_count = <span class="dv">0</span>
        <span class="kw">for</span> i in test_indices:
            test = data_matrix[i]
            prediction = nn.predict(test)
            <span class="kw">if</span> data_labels[i] == prediction:
                correct_guess_count += <span class="dv">1</span>

        avg_sum += (correct_guess_count / <span class="dt">float</span>(<span class="dt">len</span>(test_indices)))
    <span class="kw">return</span> avg_sum / <span class="dv">100</span></code></pre>

<p>The inner loop is counting the number of correct classifications which are then divided by the number of attempted classifications at the end. This gives a ratio or percentage accuracy for the ANN. Since each time an ANN is trained, its weights may be slightly different, we repeat this process 100 times in the outer loop so we can take an average of this particular ANN configuration's accuracy. In our case, a sample run of <code>neural_network_design.py</code> looks like the following:</p>

<pre><code>PERFORMANCE
-----------
5 Hidden Nodes: 0.7792
10 Hidden Nodes: 0.8704
15 Hidden Nodes: 0.8808
20 Hidden Nodes: 0.8864
25 Hidden Nodes: 0.8808
30 Hidden Nodes: 0.888
35 Hidden Nodes: 0.8904
40 Hidden Nodes: 0.8896
45 Hidden Nodes: 0.8928</code></pre>

<p>From this output we can conclude that 15 hidden nodes would be most optimal. Adding 5 nodes from 10 to 15 gets us ~1% more accuracy, whereas improving the accuracy by another 1% would require adding another 20 nodes. Increasing the hidden node count also increases computational overhead. So it would take networks with more hidden nodes longer to be trained and to make predictions. Thus we choose to use the last hidden node count that resulted in a dramatic increase in accuracy. Of course, it’s possible when designing an ANN that computational overhead is no problem and it's top priority to have the most accurate ANN possible. In that case it would be better to choose 45 hidden nodes instead of 15.</p>

<h3 id="core-ocr-functionality">Core OCR Functionality</h3>

<p>In this section we’ll talk about how the actual training occurs via backpropagation, how we can use the network to make predictions, and other key design decisions for core functionality.</p>

<h4 id="training-via-backpropagation-ocr.py">Training via Backpropagation (<code>ocr.py</code>)</h4>

<p>We use the backpropagation algorithm to train our ANN. It consists of 4 main steps that are repeated for every sample in the training set, updating the ANN weights each time.</p>

<p>First, we initialize the weights to small (between -1 and 1) random values. In our case, we initialize them to values between -0.06 and 0.06 and store them in matrices <code>theta1</code>, <code>theta2</code>, <code>input_layer_bias</code>, and <code>hidden_layer_bias</code>. Since every node in a layer links to every node in the next layer we can create a matrix that has m rows and n columns where n is the number of nodes in one layer and m is the number of nodes in the adjacent layer. This matrix would represent all the weights for the links between these two layers. Here theta1 has 400 columns for our 20x20 pixel inputs and <code>num_hidden_nodes</code> rows. Likewise, <code>theta2</code> represents the links between the hidden layer and output layer. It has <code>num_hidden_nodes</code> columns and <code>NUM_DIGITS</code> (<code>10</code>) rows. The other two vectors (1 row), <code>input_layer_bias</code> and <code>hidden_layer_bias</code> represent the biases.</p>

<pre class="sourceCode python"><code class="sourceCode python">    <span class="kw">def</span> _rand_initialize_weights(<span class="ot">self</span>, size_in, size_out):
        <span class="kw">return</span> [((x * <span class="fl">0.12</span>) - <span class="fl">0.06</span>) <span class="kw">for</span> x in np.random.rand(size_out, size_in)]</code></pre>

<pre class="sourceCode python"><code class="sourceCode python">            <span class="ot">self</span>.theta1 = <span class="ot">self</span>._rand_initialize_weights(<span class="dv">400</span>, num_hidden_nodes)
            <span class="ot">self</span>.theta2 = <span class="ot">self</span>._rand_initialize_weights(num_hidden_nodes, <span class="dv">10</span>)
            <span class="ot">self</span>.input_layer_bias = <span class="ot">self</span>._rand_initialize_weights(<span class="dv">1</span>, 
                                                                  num_hidden_nodes)
            <span class="ot">self</span>.hidden_layer_bias = <span class="ot">self</span>._rand_initialize_weights(<span class="dv">1</span>, <span class="dv">10</span>)</code></pre>

<p>The second step is <em>forward propagation</em>, which is essentially computing the node outputs as described in <a href="#sec.ocr.ann">What Are ANNs?</a>, layer by layer starting from the input nodes. Here, <code>y0</code> is an array of size 400 with the inputs we wish to use to train the ANN. We multiply <code>theta1</code> by <code>y0</code> transposed so that we have two matrices with sizes <code>(num_hidden_nodes x 400) * (400 x 1)</code> and have a resulting vector of outputs for the hidden layer of size num_hidden_nodes. We then add the bias vector and apply the vectorized sigmoid activation function to this output vector, giving us <code>y1</code>. <code>y1</code> is the output vector of our hidden layer. The same process is repeated again to compute <code>y2</code> for the output nodes. <code>y2</code> is now our output layer vector with values representing the likelihood that their index is the drawn number. For example if someone draws an 8, the value of <code>y2</code> at the 8th index will be the largest if the ANN has made the correct prediction. However, 6 may have a higher likelihood than 1 of being the drawn digit since it looks more similar to 8 and is more likely to use up the same pixels to be drawn as the 8. <code>y2</code> becomes more accurate with each additional drawn digit the ANN is trained with.</p>

<pre class="sourceCode python"><code class="sourceCode python">    <span class="co"># The sigmoid activation function. Operates on scalars.</span>
    <span class="kw">def</span> _sigmoid_scalar(<span class="ot">self</span>, z):
        <span class="kw">return</span> <span class="dv">1</span> / (<span class="dv">1</span> + math.e ** -z)</code></pre>

<pre class="sourceCode python"><code class="sourceCode python">            y1 = np.dot(np.mat(<span class="ot">self</span>.theta1), np.mat(data[<span class="st">&#39;y0&#39;</span>]).T)
            sum1 =  y1 + np.mat(<span class="ot">self</span>.input_layer_bias) <span class="co"># Add the bias</span>
            y1 = <span class="ot">self</span>.sigmoid(sum1)

            y2 = np.dot(np.array(<span class="ot">self</span>.theta2), y1)
            y2 = np.add(y2, <span class="ot">self</span>.hidden_layer_bias) <span class="co"># Add the bias</span>
            y2 = <span class="ot">self</span>.sigmoid(y2)</code></pre>

<p>The third step is <em>back propagation</em>, which involves computing the errors at the output nodes then at every intermediate layer back towards the input. Here we start by creating an expected output vector, <code>actual_vals</code>, with a <code>1</code> at the index of the digit that represents the value of the drawn digit and <code>0</code>s otherwise. The vector of errors at the output nodes, <code>output_errors</code>, is computed by subtracting the actual output vector, <code>y2</code>, from <code>actual_vals</code>. For every hidden layer afterwards, we compute two components. First, we have the next layer’s transposed weight matrix multiplied by its output errors. Then we have the derivative of the activation function applied to the previous layer. We then perform an element-wise multiplication on these two components, giving a vector of errors for a hidden layer. Here we call this <code>hidden_errors</code>.</p>

<pre class="sourceCode python"><code class="sourceCode python">            actual_vals = [<span class="dv">0</span>] * <span class="dv">10</span> 
            actual_vals[data[<span class="st">&#39;label&#39;</span>]] = <span class="dv">1</span>
            output_errors = np.mat(actual_vals).T - np.mat(y2)
            hidden_errors = np.multiply(np.dot(np.mat(<span class="ot">self</span>.theta2).T, output_errors), 
                                        <span class="ot">self</span>.sigmoid_prime(sum1))</code></pre>

<p>Weight updates that adjust the ANN weights based on the errors computed earlier. Weights are updated at each layer via matrix multiplication. The error matrix at each layer is multiplied by the output matrix of the previous layer. This product is then multiplied by a scalar called the learning rate and added to the weight matrix. The learning rate is a value between 0 and 1 that influences the speed and accuracy of learning in the ANN. Larger learning rate values will generate an ANN that learns quickly but is less accurate, while smaller values will will generate an ANN that learns slower but is more accurate. In our case, we have a relatively small value for learning rate, 0.1. This works well since we do not need the ANN to be immediately trained in order for a user to continue making train or predict requests. Biases are updated by simply multiplying the learning rate by the layer’s error vector.</p>

<pre class="sourceCode python"><code class="sourceCode python">            <span class="ot">self</span>.theta1 += <span class="ot">self</span>.LEARNING_RATE * np.dot(np.mat(hidden_errors), 
                                                       np.mat(data[<span class="st">&#39;y0&#39;</span>]))
            <span class="ot">self</span>.theta2 += <span class="ot">self</span>.LEARNING_RATE * np.dot(np.mat(output_errors), 
                                                       np.mat(y1).T)
            <span class="ot">self</span>.hidden_layer_bias += <span class="ot">self</span>.LEARNING_RATE * output_errors
            <span class="ot">self</span>.input_layer_bias += <span class="ot">self</span>.LEARNING_RATE * hidden_errors</code></pre>

<h4 id="testing-a-trained-network-ocr.py">Testing a Trained Network (<code>ocr.py</code>)</h4>

<p>Once an ANN has been trained via backpropagation, it is fairly straightforward to use it for making predictions. As we can see here, we start by computing the output of the ANN, <code>y2</code>, exactly the way we did in step 2 of backpropagation. Then we look for the index in the vector with the maximum value. This index is the digit predicted by the ANN.</p>

<pre><code>    def predict(self, test):
        y1 = np.dot(np.mat(self.theta1), np.mat(test).T)
        y1 =  y1 + np.mat(self.input_layer_bias) # Add the bias
        y1 = self.sigmoid(y1)

        y2 = np.dot(np.array(self.theta2), y1)
        y2 = np.add(y2, self.hidden_layer_bias) # Add the bias
        y2 = self.sigmoid(y2)

        results = y2.T.tolist()[0]
        return results.index(max(results))</code></pre>

<h4 id="other-design-decisions-ocr.py">Other Design Decisions (<code>ocr.py</code>)</h4>

<p>Many resources are available online that go into greater detail on the implementation of backpropagation. One good resource is from a <a href="http://www.willamette.edu/~gorr/classes/cs449/backprop.html">course by the University of Willamette</a>. It goes over the steps of backpropagation and then explains how it can be translated into matrix form. While the amount of computation using matrices is the same as using loops, the benefit is that the code is simpler and easier to read with fewer nested loops. As we can see, the entire training process is written in under 25 lines of code using matrix algebra.</p>

<p>As mentioned in the introduction of <a href="#sec.ocr.decisions">Design Decisions in a Simple OCR System</a>, persisting the weights of the ANN means we do not lose the progress made in training it when the server is shut down or abruptly goes down for any reason. We persist the weights by writing them as JSON to a file. On startup, the OCR loads the ANN’s saved weights to memory. The save function is not called internally by the OCR but is up to the server to decide when to perform a save. In our case, the server saves the weights after each update. This is a quick and simple solution but it is not optimal since writing to disk is time consuming. This also prevents us from handling multiple concurrent requests since there is no mechanism to prevent simultaneous writes to the same file. In a more sophisticated server, saves could perhaps be done on shutdown or once every few minutes with some form of locking or a timestamp protocol to ensure no data loss.</p>

<pre class="sourceCode python"><code class="sourceCode python">    <span class="kw">def</span> save(<span class="ot">self</span>):
        <span class="kw">if</span> not <span class="ot">self</span>._use_file:
            <span class="kw">return</span>

        json_neural_network = {
            <span class="st">&quot;theta1&quot;</span>:[np_mat.tolist()[<span class="dv">0</span>] <span class="kw">for</span> np_mat in <span class="ot">self</span>.theta1],
            <span class="co">&quot;theta2&quot;</span>:[np_mat.tolist()[<span class="dv">0</span>] <span class="kw">for</span> np_mat in <span class="ot">self</span>.theta2],
            <span class="co">&quot;b1&quot;</span>:<span class="ot">self</span>.input_layer_bias[<span class="dv">0</span>].tolist()[<span class="dv">0</span>],
            <span class="co">&quot;b2&quot;</span>:<span class="ot">self</span>.hidden_layer_bias[<span class="dv">0</span>].tolist()[<span class="dv">0</span>]
        };
        <span class="kw">with</span> <span class="dt">open</span>(OCRNeuralNetwork.NN_FILE_PATH,<span class="st">&#39;w&#39;</span>) <span class="ch">as</span> nnFile:
            json.dump(json_neural_network, nnFile)

    <span class="kw">def</span> _load(<span class="ot">self</span>):
        <span class="kw">if</span> not <span class="ot">self</span>._use_file:
            <span class="kw">return</span>

        <span class="kw">with</span> <span class="dt">open</span>(OCRNeuralNetwork.NN_FILE_PATH) <span class="ch">as</span> nnFile:
            nn = json.load(nnFile)
        <span class="ot">self</span>.theta1 = [np.array(li) <span class="kw">for</span> li in nn[<span class="st">&#39;theta1&#39;</span>]]
        <span class="ot">self</span>.theta2 = [np.array(li) <span class="kw">for</span> li in nn[<span class="st">&#39;theta2&#39;</span>]]
        <span class="ot">self</span>.input_layer_bias = [np.array(nn[<span class="st">&#39;b1&#39;</span>][<span class="dv">0</span>])]
        <span class="ot">self</span>.hidden_layer_bias = [np.array(nn[<span class="st">&#39;b2&#39;</span>][<span class="dv">0</span>])]</code></pre>

<h2 id="conclusion">Conclusion</h2>

<p>Now that we’ve learned about AI, ANNs, backpropagation, and building an end-to-end OCR system, let’s recap the highlights of this chapter and the big picture.</p>

<p>We started off the chapter by giving background on AI, ANNs, and roughly what we will be implementing. We discussed what AI is and examples of how it’s used. We saw that AI is essentially a set of algorithms or problem-solving approaches that can provide an answer to a question in a similar manner as a human would. We then took a look at the structure of a Feedforward ANN. We learned that computing the output at a given node was as simple as summing the products of the outputs of the previous nodes and their connecting weights. We talked about how to use an ANN by first formatting the input and partitioning the data into training and validation sets.</p>

<p>Once we had some background, we started talking about creating a web-based, client-server system that would handle user requests to train or test the OCR. We then discussed how the client would interpret the drawn pixels into an array and perform an HTTP request to the OCR server to perform the training or testing. We discussed how our simple server read requests and how to design an ANN by testing performance of several hidden node counts. We finished off by going through the core training and testing code for backpropagation.</p>

<p>Although we’ve built a seemingly functional OCR system, this chapter simply scratches the surface of how a real OCR system might work. More sophisticated OCR systems could have pre-processed inputs, use hybrid ML algorithms, have more extensive design phases, or other further optimizations.</p>
  </body>
</html>
